<?php

class Controller_Cart extends Controller_Website
{
    protected $allowedSection = array('shop');

    public function  before()
    {
//		if(empty($_SESSION)) {
//			session_start();
//		}
        parent::before();
        $this->db = Database::instance();
        $this->mod = Model::factory('Directory');
        $this->section = 'shop';
    }

    public function actionAdd($action, $id)
    {

        $section = $this->section;
        if (Request::$isAjax) {
            $response['errors'] = array();
            $item = $this->db->query('SELECT * FROM `directoryItems` WHERE `isCategory`=0 AND `id`=?', array($id))->fetch();

            if(!$item or !in_array($item['section'], $this->allowedSection)) {
                $response['errors'][] = 'Invalid id. Refresh page and try again.';
            }

            if (empty($response['errors'])) {
                switch($action) {
                    case 'get':

                        $image = $this->direc->getItemImages($id, $this->section, $order = 'name', $orderDir = 'ASC');
                        $image = array_shift($image);
                        $bigImg = $this->direc->imagePath($image, 'shopItemBig', $extension = 'jpg');
                        $zoomImg = $this->direc->imagePath($image, 'shopItemZoom', $extension = 'jpg');

                        $result = array(
                            'name'          => $item['name'],
                            'minitext'      => $item['text1'],
                            'fulltext'      => $item['text2'],
                            'price'         => $item['price'],
                            'big_img_url'   => $bigImg,
                            'zoom_img_url'   => $zoomImg,
                            'section'       => 'shop'
                        );
                        $response['success'] = $result;
                        break;

                    case 'set':

//                        if (empty($_POST['color']) || empty($_POST['size']) ) {
//                            $response['errors'][] = 'No color or size. Refresh page and try again.';
//                            break;
//                        }


                        if (!isset($_SESSION['cart'][$section])) {
                            $_SESSION['cart'][$section] = array();
                        }

                        foreach ($_SESSION['cart'][$section] as $k => $v) {
                            if ($v['id'] == $_POST['id'] ) {
                                if(isset($_POST['quantity'])){
                                    $_SESSION['cart'][$section][$k]['quantity']+= (int)$_POST['quantity'];
                                }
                                else{
                                    $_SESSION['cart'][$section][$k]['quantity']++;
                                }

                                $response['errors'][] = 'This is already in cart.';
                                $itemsCount = 0;
                                foreach ($_SESSION['cart']['shop'] as $shopItem){
                                    $itemsCount+=$shopItem['quantity'];
                                }
                                if($itemsCount > 99){
                                    $itemsCount = '99+';
                                }
                                $response['eRquantity'] = $itemsCount;
                                break(2);
                            }
                        }

                        $_SESSION['cart'][$section][] = array(
                            'id'		    => $_POST['id'],
                            'name'		    => $item['name'],
                            'price'		    => $item['price'],
                            'token'		    => $item['token'],
                            'text'		    => $item['text1'],
                            'fulltext'		=> $item['text2'],
                            'quantity'      => (isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1),
                            'section'       => 'shop',
                            'settings'      => array('size' =>'',
                                                     'color' =>'')
                        );


                        $itemsCount = 0;
                        foreach ($_SESSION['cart']['shop'] as $shopItem){
                            $itemsCount+=$shopItem['quantity'];
                        }
                        if($itemsCount > 99){
                            $itemsCount = '99+';
                        }
                        $response['success'] = $itemsCount;
                        break;
                }
            }

            if (!count($response['errors'])) {
                unset($response['errors']);
            }
            $this->autoRender = false;
            $this->response->setHeader('Content-Type', 'application/json');
            $this->response->body = json_encode($response);
        } else {
            $this->response->redirect('/commerce/checkout/');
        }
    }

    public function actionCart()
    {
        if(Request::$isAjax)
        {

            $this->autoRender = FALSE;
            $total = 0;
            $id = 0;
            $cart_bg = (empty($_SESSION['cart']['shop'])?'background:#ffffff':'');
            echo "<div class='cart_items_all' style='".$cart_bg."'>";
            if(empty($_SESSION['cart']['shop']))
            {
                echo "<div class='cart_header'>
                                <h1>Your Cart is Empty</h1>
                            </div>";
                exit;
            }

            print <<<HERE

                            <div class="cart_header">
                                <span class="shopping_cart_img"></span>
                                <span class="shopping_cart_text">Shopping Cart</span>
                            </div>
                            <div class="cart_fields">
                                <span class="field_image">Item</span>
                                <span class="field_description">Description</span>
                                <span class="field_quantity">Quantity</span>
                                <span class="field_price">Price</span>
                                <span class="field_subtotal">Total Price</span>
                                <div class="clear"></div>
                            </div>

                            <div class="cart_items_wrapper">
HERE;
            foreach ($_SESSION['cart']['shop'] as $key=>$item)
            {
                $total = $total + $item['price']*$item['quantity'];
                $subtotal = $item['price']*$item['quantity'];

                $image = Model::factory('directory')->getItemImages($item['id'], $this->section, $order = 'name', $orderDir = 'ASC');
                $image = array_shift($image);
                $img_url_preview = Model::factory('directory')->imagePath($image, 'cartItemPreview', $extension = 'jpg');
                print <<<HERE

                        <div class="cart_item" data-id="{$item['id']}">
                            <div class="cart_item_image">
                                <img src="{$img_url_preview}"/>
                            </div>

                            <div class="cart_item_description">
                                <h3>{$item['name']}</h3>
                                <div>{$item['text']}</div>
                            </div>
                            <div class="cart_item_quantity">
                                <input type="text" size="1" value="{$item['quantity']}"/>
                                <img src="/images/galochka.png">
                            </div>
                            <div class="cart_item_price">$ {$item['price']}</div>
                            <div class="cart_item_subtotal">$ {$subtotal}</div>
                            <div class="cart_item_remove">
                                <span class="cart_item_remove_btn" id="{$key}"></span>
                            </div>
                            <div class="clear"></div>

                            <div class="clear"></div>
                        </div>

HERE;
            }

            print <<<HERE

                            </div>
                            <div class="cart_footer">
                                <div class="cart_footer_left">
                                    <a class="back_to_shop" href="#">← Back to Shop Online</a>
                                </div>

                                <div class="cart_total">
                                    TOTAL: <span>$ {$total}</span>
                                </div>
                                <div class="cart_stripe"></div>
                            </div>
                            <div class="proceed_checkout_wrapper">
                                <div class="button proceed_checkout">
                                    Checkout
                                </div>
                            </div>
                            <div class="cart_bottom">

                            </div>

                            <script type='text/javascript'>
                            $(function()
                                {
                                        $('.cart_items_wrapper').jScrollPane({autoReinitialise:true,scrollbarWidth:5,verticalDragMaxHeight:50,verticalDragMinHeight:25,contentWidth:690});
                                });
                            </script>


HERE;


//            $(function()
//                                {
//                                        $('.cart_items_wrapper').jScrollPane({scrollbarWidth:5,verticalDragMaxHeight:100,verticalDragMinHeight:25,contentWidth:950,verticalGutter:5});
//                                });
//                            </script>

        }
    }

    public function actionFlush()
    {
        if (Request::$isAjax) {
            $this->autoRender = false;
            $this->response->setHeader('Content-Type', 'application/json');
            $_SESSION['cart'][$this->section] = array();
            $this->response->body = json_encode('Done!');
        }
    }

    public function actionCartDeleteItem()
    {
        $this->autoRender = false;
        if(Request::$isAjax)
        {
            $total =0;
            $quant=0;
            $id = $_POST['id'];
            if(isset($_SESSION['cart'][$this->section][$id]))
            {
                unset($_SESSION['cart'][$this->section][$id]);
            }
            $response['success'] = count($_SESSION['cart'][$this->section]);

            foreach ($_SESSION['cart']['shop'] as $key=>$item)
            {
                $total = $total + $item['price']*$item['quantity'];
                $quant+=$_SESSION['cart']['shop'][$key]['quantity'];
            }
            $response['total'] = $total;
            $response['quant'] = $quant;
        }
        $this->response->setHeader('Content-Type', 'application/json');
        $this->response->body = json_encode($response);

    }

    public function actionQuantity()
    {
        $this->autoRender = false;
        if(Request::$isAjax)
        {
            $quantity = $_POST['quantity'];
            $id = $_POST['id'];
            if(isset($_SESSION['cart'][$this->section][$id]))
            {
                $_SESSION['cart'][$this->section][$id]['quantity'] = $quantity;
            }
            $response['success'] = count($_SESSION['cart'][$this->section]);
        }

    }
    public function actionCartUpdate()
    {
        if(Request::$isAjax)
        {
            $this->autoRender = FALSE;
            $total = 0;
            $quant = 0;
            foreach ($_SESSION['cart']['shop'] as $key=>$item)
            {
                $cartInfo['items'][$key] = $item;

                $imgurl = $this->manager->getImageForCartUrl($item['id']);
                $cartInfo['items'][$key]['imgurl']=$imgurl;
                $total = $total + $item['price']*$item['quantity'];
                $subtotal = $item['price']*$item['quantity'];
                $quant+=$_SESSION['cart']['shop'][$key]['quantity'];
            }
            $cartInfo['total']=$total;
            $cartInfo['quant']=$quant;

        }

        $this->response->setHeader('Content-Type', 'application/json');
        $this->response->body = json_encode($cartInfo);


    }
}

